package com.visionet.waveletData.web.common.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import kp.client.constants.OverwriteType;
import kp.client.core.KuaipanApi;
import kp.client.core.KuaipanApiClient;
import kp.client.model.AccountInfo;
import kp.client.model.CreateFolder;
import kp.client.model.DownloadFile;
import kp.client.model.MetaData;
import kp.client.model.Shares;
import kp.client.model.UploadFile;
import kp.client.model.UploadLocate;

import org.json.JSONArray;
import org.json.JSONObject;
import org.scribe.builder.ServiceBuilder;
import org.scribe.model.Token;

import com.visionet.waveletData.web.common.utilities.MessageSourceHelper;
import com.visionet.waveletData.web.common.utilities.props.PropsUtil;
import com.visionet.waveletData.web.common.utilities.string.StringPool;
import com.visionet.waveletData.web.entity.vo.KPVo;
import com.visionet.waveletData.web.service.KeyWord;

/**
 * @author add by WangBo 2013-2-16
 */

public class KPUtil {
	
	private KPUtil() {}
	
	private static final String KP_ROOT_DIRECTORY = MessageSourceHelper.GetMessages("app.common.utils.KPUtil.allfiles");
	
	private static Token setToken(String accessToken, String secret){
		Token token = new Token(accessToken, secret);
		return token;
	}
	
	//获取用户信息
	public static KPVo kpAccountInfo(String accessToken, String secret) throws Exception {
		//获取到的access_token
		Token token = setToken(accessToken, secret);
		AccountInfo accountInfo = new AccountInfo();
		KuaipanApiClient client = new ServiceBuilder().provider(KuaipanApi.class).build();
		JSONObject obj = client.doCall(token, accountInfo );
		String userName = obj.getString("user_name");
		KPVo kpvo = new KPVo();
		kpvo.setUserName(userName);
		return kpvo;
	}
	
	/**
	 * 获取目录/文件信息
	 * @param path 当前路径
	 */
	public static List<KPVo> metaData(String accessToken, String secret, String path) throws Exception {
		return metaData(accessToken, secret, path, 0, 0);
	}
	
	/**
	 * 获取目录/文件信息 带分页
	 * @param path 当前路径,需要完整路径 ,如果是根路径,则为 / 或者 ""
	 * @param page 当前页
	 * @param pageSize 翻页数量
	 */
	public static List<KPVo> metaData(String accessToken, String secret, String path, Integer page, Integer pageSize) throws Exception {
		Token token = setToken(accessToken, secret);
		MetaData metaData = new MetaData(toUtf8String(path));
		
		if(Validator.isNotNull(page)){
			metaData.page(page);
		}
		
		if(Validator.isNotNull(pageSize)){
			metaData.pageSize(pageSize);
		}
		
		KuaipanApiClient client = new ServiceBuilder().provider(KuaipanApi.class).build();
		JSONObject obj = client.doCall(token, metaData );
		//上级目录
		String wholePath = obj.getString("path");
		JSONArray list = obj.getJSONArray("files");
		List<KPVo> metaList = new ArrayList<KPVo>();
		for(int i=0; i<list.length(); i++){
			JSONObject jsonobj = list.getJSONObject(i);
			String delFlag = jsonobj.getString("is_deleted");
			if("false".equals(delFlag)){
				//文件名
				String fileName = jsonobj.getString("name");
				//文件类型
				String fileType = jsonobj.getString("type");
				//单位 kb
				int mSize = 1024;
				int fileSize = jsonobj.getInt("size") / mSize; 
				if(fileSize == 0){
					fileSize = 1;
				}
				String modifyTime = jsonobj.getString("modify_time");
				KPVo kp = new KPVo();
				kp.setFileName(fileName);
				kp.setParentPath(getParentPath(wholePath));
				kp.setWholeCurrentPath(wholePath);
				kp.setFileSize(fileSize);
				kp.setFileType(fileType);
				kp.setModifyTime(modifyTime);
				metaList.add(kp);
			}
		}
		return metaList;
	}
	
	
	/**
	 * 创建文件夹
	 * @param folderName 文件夹名称 完整路径
	 * 例: 在/file下创建一个excel文件夹 ,则folderName 为 /file/excel
	 */
	public static boolean createFolder(String accessToken, String secret, String folderName) throws Exception {
		Token token = setToken(accessToken, secret);
		String root = "app_folder";
		CreateFolder createFolder = new CreateFolder(root, folderName);
		KuaipanApiClient client = new ServiceBuilder().provider(KuaipanApi.class).build();
		JSONObject obj = client.doCall(token, createFolder );
		if(obj != null && "ok".equals(obj.getString("msg"))){
			return true;
		}
		return false;
	}
	
	/**
	 * @param filePath 文件名,带完整路径
	 * @param catalog	上传的目录 ,完整路径
	 */
	public static boolean uploadFile(String accessToken, String secret, String filePath, String catalog) throws Exception {
		String catalogBackup = catalog;
		Token token = setToken(accessToken, secret);
		KuaipanApiClient client = new ServiceBuilder().provider(KuaipanApi.class).build();
		UploadLocate uploadLocate = new UploadLocate();
		//获取文件上传地址
		String uploadUrl = client.doCall(token, uploadLocate).getString("url");
		
		File file = new File(filePath);
		String fileName = file.getName();
		
		if(!catalogBackup.startsWith(StringPool.SLASH)){
			catalogBackup = StringPool.SLASH + catalogBackup;
		}
		
		if(catalogBackup.endsWith(StringPool.SLASH)){
			catalogBackup = catalogBackup.substring(0, catalogBackup.length() - 1);
		}
		
		String root = "app_folder";
		String path = catalogBackup + StringPool.SLASH +fileName;
		
		String separator = System.getProperty("file.separator");
		String newFilePath = filePath.replace("/", separator);
		UploadFile uploadFile = new UploadFile(OverwriteType.True, root, path, uploadUrl, newFilePath);
		JSONObject obj = client.doCall(token, uploadFile);
		if(obj != null && !obj.getString("file_id").isEmpty()){
			return true;
		}
		return false;
	}
	
	/**
	 * 返回上级路径 
	 * 不带文件名
	 * 例: / 或者 /path 返回/ /path/path1  返回/path  /path/path1/path2 返回/path/path1
	 * 带文件名  
	 * 例: /path/path1/file.txt 返回/path
	 * @param currPath
	 * @return
	 */
	public static String getParentPath(String currPath){
		
		String currPathBackup = currPath;
		
		if(currPathBackup.indexOf(StringPool.PERIOD) != -1){
			int lastIndexOfSlash = currPathBackup.lastIndexOf(StringPool.SLASH);
			currPathBackup = currPathBackup.substring(0, lastIndexOfSlash);
		}
		
		String[] paths = currPathBackup.split("/");
		
		int pathLength = paths.length;
		
		StringBuffer parentPath = new StringBuffer("");
		
		switch(pathLength){
		case 0:
		case 2:
			parentPath.append(StringPool.SLASH);
			break;
		default:
			for(int i=0; i<pathLength - 2; i++){
				parentPath.append(parentPath + StringPool.SLASH + paths[i+1]);
			}
			break;
		}
		
		return parentPath.toString();
	}
	
	/**
	 * 获取所有路径 
	 * @return
	 */
	public static List<KPVo> wholePathList(String path, List<KPVo> metaList){
		if(metaList == null){
			metaList = new ArrayList<KPVo>();
		}
		KPVo kp = new KPVo();
		kp.setWholeCurrentPath(path);
		if(StringPool.SLASH.equals(path) || "".equals(path)){
			//如果是 / 则已经到达最顶层
			kp.setPath(KP_ROOT_DIRECTORY);
			metaList.add(kp);
			return metaList;
		}else{
			//否则就截取最后一段字符串作为当前目录
			int lastSlashIndex = path.lastIndexOf(StringPool.SLASH);
			String currPath = path.substring(lastSlashIndex + 1);
			kp.setPath(currPath);
		}
		metaList.add(kp);
		String parentPath = getParentPath(path);
		return wholePathList(parentPath, metaList);
	}
	
	public static List<KPVo> wholePathList(String path){
		List<KPVo> metaList = wholePathList(path, null);
		List<KPVo> newMetaList = new ArrayList<KPVo>();
		int ms = metaList.size();
		for(int i=ms-1; i>=0; i--){
			newMetaList.add(metaList.get(i));
		}
		return newMetaList;
	}
	
	public static String shareKpFile(String accessToken, String secret, String filePath) throws Exception {
		Token token = setToken(accessToken, secret);
		String utf8FileName = toUtf8String(filePath);
		Shares shares = new Shares(utf8FileName);
		KuaipanApiClient client = new ServiceBuilder().provider(KuaipanApi.class).build();
		JSONObject obj = client.doCall(token, shares );
		return obj.getString("url");
	}
	
	public static String toUtf8String(String s) throws Exception {  
	    if (s == null || s.equals("")) {  
	        return null;  
	    }  
	    StringBuffer sb = new StringBuffer();  
	        char c;  
	        for (int i = 0; i < s.length(); i++) {  
	            c = s.charAt(i);  
	            if (c >= 0 && c <= 255) {  
	                sb.append(c);  
	            } else {  
	                byte[] b;  
	                b = Character.toString(c).getBytes("utf-8");  
	                for (int j = 0; j < b.length; j++) {  
	                    int k = b[j];  
	                    if (k < 0)  
	                        k += 256;  
	                    sb.append("%" + Integer.toHexString(k).toUpperCase());  
	                }  
	            }  
	        }  
	    return sb.toString();  
	}  
	
	public static void main(String[] args) throws Exception {
		String accessToken = "01b7cf6e39b903de1e44a61d";
		String secret = "c95ab6ae4524445fb140732d78dd08e3";
//		String path = "kuaipan.txt";
//		String filePath = shareKpFile(accessToken, secret, path);
//		System.out.println(filePath);
//		String fileName = "/sql.txt";
//		String utf8FileName = toUtf8String(fileName);
//		System.out.println(utf8FileName);
//		System.out.println(shareKpFile(accessToken, secret, fileName));
		metaData(accessToken, secret, "/");
	}
	
	
	
}

